package com.jsits.v2x.common.connection.ftp;

import com.jsits.v2x.common.timer.TimerMgr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public abstract class FtpBase
{
	/*
	 * 日志
	 */
	private static Logger logger = LoggerFactory.getLogger(FtpBase.class);
	
	/*
	 * 定时检测服务端、客户端状态定时器编号
	 */
	private int timerId;
	
	/*
	 * 服务端信息
	 */
	protected ServerInfo serverInfo;	
	
	/*
	 * 获取服务端信息	
	 */
	public ServerInfo getServerInfo() 
	{
		return serverInfo;
	}

	/*
	 * 设置服务器信息，配置用
	 */
	public void setServerInfo(ServerInfo serverInfo) 
	{
		this.serverInfo = serverInfo;
	}
	
	/*
	 * 建立服务端、客户端连接
	 */
	public boolean connect() 
	{
		boolean retValue = true;
		retValue = connectServer();
		
		timerId = TimerMgr.getInstance().setTimer(this, "checkServerStatus", serverInfo.getInterval(), false);
		if (timerId == 0) 
		{
			logger.error("Set check server status timer failed");
			retValue = false;
		}
		
		return retValue;
	}
	
	/*
	 * 断开服务端、客户端连接
	 */
	public void disConnect() 
	{
		if (timerId != 0)
		{
			TimerMgr.getInstance().killTimer(timerId);
		}
		disConnectServer();
	}
	
	/*
	 * 定时检查连接状态
	 */
	public void checkServerStatus() 
	{
		//获取当前时间
		long timeStamp = new Date().getTime();
		
		//比较当前时间与最后一次心跳时间，若大于指定时间则认为心跳超时
		if ((timeStamp - serverInfo.getTimeStamp()) > serverInfo.getTimeout()) 
		{
			logger.warn("Data receive from connection is time out, reconnect");
			
			serverInfo.setStatus(false);
			
			//重新建立连接
			disConnectServer();
			connectServer();
		}
	}
	
	/*
	 * 建立连接接口，由子类实现
	 */
	protected boolean connectServer()
  	{	
  		return true;
  	}
  	
    /*
     * 断开连接接口，由子类实现
     */
	protected void disConnectServer()
  	{
  	}
}
